﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AliyunOpenSearch4Net.Base;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace AliyunOpenSearch4Net.Search
{
    class SearchRequest : RequestBase<Response<SearchResult>>
    {
        public SearchRequest()
            : base("search")
        {

        }

        public string IndexName { get; set; }

        public string Query { get; set; }

        public string FetchFields { get; set; }

        public string QP { get; set; }

        public bool Disable { get; set; }

        public string FirstFormulaName { get; set; }

        public string FormulaName { get; set; }

        public SearchSummary Summary { get; set; }

        protected override void RegisterQueryItems(IList<KeyValuePair<string, string>> list)
        {
            list.Add("index_name", IndexName);
            list.Add("query", Query);

            if (!string.IsNullOrEmpty(FetchFields))
                list.Add("fetch_fields", FetchFields);

            if (!string.IsNullOrEmpty(QP))
                list.Add("qp", QP);

            if (Disable)
                list.Add("disable", "true");

            if (!string.IsNullOrEmpty(FirstFormulaName))
                list.Add("first_formula_name", FirstFormulaName);

            if (!string.IsNullOrEmpty(FormulaName))
                list.Add("formula_name", FormulaName);

            if (Summary != null)
                list.Add("summary", Summary.ToString());
        }
    }

    /// <summary>
    /// Search result
    /// </summary>
    public class SearchResult
    {
        /// <summary>
        /// The time which was taken by the search
        /// </summary>
        /// <value>
        /// The taken time by the search.
        /// </value>
        [JsonProperty("searchtime")]
        public float SearchTime { get; set; }

        /// <summary>
        /// Gets or sets the total.
        /// </summary>
        /// <value>
        /// The total.
        /// </value>
        [JsonProperty("total")]
        public int Total { get; set; }

        /// <summary>
        /// Gets or sets the number.
        /// </summary>
        /// <value>
        /// The number.
        /// </value>
        [JsonProperty("num")]
        public int Num { get; set; }

        /// <summary>
        /// Gets or sets the view total.
        /// </summary>
        /// <value>
        /// The view total.
        /// </value>
        [JsonProperty("viewtotal")]
        public int ViewTotal { get; set; }

        /// <summary>
        /// Gets or sets the items.
        /// </summary>
        /// <value>
        /// The items.
        /// </value>
        [JsonProperty("items")]
        public JArray Items { get; set; }

        /// <summary>
        /// Gets or sets the facet.
        /// </summary>
        /// <value>
        /// The facet.
        /// </value>
        [JsonProperty("facet")]
        public JArray Facet { get; set; }
    }
}
